<template>
  <div class="formily-wrapper">
    <form-core
      v-if="hasOwnPro(schema, 'properties') && schema.type == 'object'"
      :schema="schema"
      @update:form="(formData) => this.$form = formData"
    >
      <!-- <template #default="">
        <slot name="form-item" v-bind="{schema, formData}"></slot>
      </template> -->
    </form-core>
  </div>
</template>
<script>
import FormCore from "./FormCore";
import { isObject, inPrimitive, hasOwnPro } from "./utils";
export default {
  name: 'Formily',
  components: {
    FormCore,
  },
  props: {
    schema: {
      type: Object,
      required: true
    },
    form: {
      type: [Object, Array]
    }
  },
  provide() {
    return {
      $originForm: this.form,
      $formData: this.formData
    }
  },
  data() {
    return {
      formData: merge(this.generateFormData(this.schema), this.form)
    }
  },
  created() {
    // if(!this.formData) {
    //   this.formData = {};
    // }
    console.log(this.generateFormData(this.schema));


    //const formData = merge(this.generateFormData(this.schema), this.formData);
    // 如果是一个对象，给其放到数组中。
    // 目的是dom结构好遍历
    // if(!Array.isArray(formData)) {
    //   this.formDatas = [formData];
    // }
  },
  methods: {
    hasOwnPro,
    /**
     * 生成默认值的 formData数据
     * @param { json schema } schema 
     * @param { object | undefined } formData 
     * @param { string | undefined } field
     * formData, field 是函数递归自身的递归字段
     */
    generateFormData(schema, formData, field) {
      const type = schema.type;
      const properties = schema.properties;
      if(type === 'array' && schema.items) {
        formData = formData || [];
        const curFormData = this.generateFormData(schema.items, {}, field);
        formData.push(curFormData);
      }else if(type === 'object' && isObject(properties)) {
        formData = formData || {};
        Object.keys(properties).forEach(property => {
          const subSchema = properties[property];
          // 如果是基本数据类型
          if(inPrimitive(subSchema.type)) {
            formData[property] = this.getDftValue(subSchema);
          }else {
            const typeMad = { 'array': [], 'object': {} };
            const curFormData = this.generateFormData(subSchema, typeMad[subSchema.type], property);
            formData[property] = curFormData;
          }
        });
      }
      return formData;
    },
    // 设置不同类型的默认值
    getDftValue(schema) {
      const type = schema.type;
      if(hasOwnPro(schema, 'default')) {
        return schema.default;
      }
      // 不在dftValueMap中的类型，都返回undefined
      const dftValueMap = {
        string: '',
        boolean: false
      }
      return dftValueMap[type];
    },
  }
}
</script>